package com.leetcode.partition7;

import com.leetcode.common.TreeNode;

/**
 * @author `RKC`
 * @date 2021/8/22 8:25
 */
public class LC669修剪二叉搜索树 {

    public static TreeNode trimBST(TreeNode root, int low, int high) {
        return recursion(root, low, high);
    }

    public static void main(String[] args) {
        TreeNode root = new TreeNode(3, new TreeNode(0, null, new TreeNode(2, new TreeNode(1), null)), new TreeNode(4));
        root = trimBST(root, 1, 3);
        System.out.println(root.val);
    }

    private static TreeNode recursion(TreeNode root, int low, int high) {
        if (root == null) return null;
        //寻找符合区间[low, high]的结点
        if (root.val < low) return recursion(root.right, low, high);
        if (root.val > high) return recursion(root.left, low, high);

        root.left = recursion(root.left, low, high);        //接入符合条件的左孩子
        root.right = recursion(root.right, low, high);      //接入符合条件的右孩子
        return root;
    }

    private static TreeNode iteration(TreeNode root, int low, int high) {
        if (root == null) return null;
        //让头结点移动到[low, high]区间内
        while (root.val < low || root.val > high) {
            if (root.val < low) root = root.right;
            else root = root.left;
        }
        TreeNode cur = root;
        //处理左孩子元素小于low的情况
        while (cur != null) {
            while (cur.left != null && cur.left.val < low) {
                cur.left = cur.left.right;
            }
            cur = cur.left;
        }
        cur = root;
        //处理右孩子大于high的情况
        while (cur != null) {
            while (cur.right != null && cur.right.val > high) {
                cur.right = cur.right.left;
            }
            cur = cur.right;
        }
        return root;
    }
}
